package com.als;

import com.als.config.DatabaseConfig;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.sql.*;
import java.util.List;

/**
 * MySQL推荐结果服务类
 */
@Slf4j
public class MySQLRecommendationService {

    private final DatabaseConfig dbConfig;

    public MySQLRecommendationService() {
        this.dbConfig = YamlConfigReader.loadDatabaseConfig("application.yml");
    }

    /**
     * 保存单条推荐记录（JDBC方式）
     */
    public void saveSingleRecommendation(int userId, int itemId, double rating, int rank) {
        String sql = "INSERT INTO user_recommendations (user_id, item_id, predicted_rating, ranking) VALUES (?, ?, ?, ?) " +
                "ON DUPLICATE KEY UPDATE predicted_rating = VALUES(predicted_rating), ranking = VALUES(ranking)";

        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, userId);
            pstmt.setInt(2, itemId);
            pstmt.setDouble(3, rating);
            pstmt.setInt(4, rank);

            pstmt.executeUpdate();

        } catch (Exception e) {
            log.error("保存推荐记录失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 批量保存推荐结果
     */
    public void batchSaveRecommendations(List<Recommendation> recommendations) {
        String sql = "INSERT INTO user_recommendations (user_id, item_id, predicted_rating, ranking) VALUES (?, ?, ?, ?)";

        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            conn.setAutoCommit(false);  // 开启事务

            for (Recommendation rec : recommendations) {
                pstmt.setInt(1, rec.getUserId());
                pstmt.setInt(2, rec.getItemId());
                pstmt.setDouble(3, rec.getRating());
                pstmt.setInt(4, rec.getRank());
                pstmt.addBatch();
            }

            pstmt.executeBatch();
            conn.commit();  // 提交事务

            log.info("批量保存 {} 条推荐记录成功", recommendations.size());

        } catch (Exception e) {
            log.error("批量保存推荐记录失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 获取数据库连接
     */
    private Connection getConnection() throws SQLException {
        return DriverManager.getConnection(dbConfig.getUrl(), dbConfig.getUsername(), dbConfig.getPassword());
    }

    /**
     * 推荐记录实体类
     */
    @Data
    public static class Recommendation {
        private int userId;
        private int itemId;
        private double rating;
        private int rank;
        private Timestamp createTime;
    }
}
